/// 歌词行数据模型
class LyricLine {
  final Duration time;
  final String text;

  LyricLine({
    required this.time,
    required this.text,
  });
}

/// 歌词解析工具类
class LyricParser {
  /// 解析LRC格式歌词
  static List<LyricLine> parseLyric(String? lyricText) {
    if (lyricText == null || lyricText.isEmpty) {
      return [];
    }

    final List<LyricLine> lyrics = [];
    final lines = lyricText.split('\n');

    for (String line in lines) {
      line = line.trim();
      if (line.isEmpty) continue;

      // 匹配时间标签格式 [mm:ss.xx] 或 [mm:ss]
      final RegExp timeRegex = RegExp(r'\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\](.*)');
      final match = timeRegex.firstMatch(line);

      if (match != null) {
        final minutes = int.parse(match.group(1)!);
        final seconds = int.parse(match.group(2)!);
        final milliseconds = match.group(3) != null 
            ? int.parse(match.group(3)!.padRight(3, '0').substring(0, 3))
            : 0;
        final text = match.group(4)?.trim() ?? '';

        // 只添加有文本内容的歌词行
        if (text.isNotEmpty) {
          final time = Duration(
            minutes: minutes,
            seconds: seconds,
            milliseconds: milliseconds,
          );

          lyrics.add(LyricLine(
            time: time,
            text: text,
          ));
        }
      }
    }

    // 按时间排序
    lyrics.sort((a, b) => a.time.compareTo(b.time));
    return lyrics;
  }

  /// 根据当前播放时间找到当前歌词行索引
  static int getCurrentLyricIndex(List<LyricLine> lyrics, Duration currentTime) {
    if (lyrics.isEmpty) return -1;

    // 如果当前时间小于第一行歌词的时间，返回-1（还没开始）
    if (currentTime < lyrics[0].time) {
      return -1;
    }

    // 找到最后一个时间小于等于当前时间的歌词行
    int currentIndex = -1;
    for (int i = 0; i < lyrics.length; i++) {
      if (lyrics[i].time <= currentTime) {
        currentIndex = i;
      } else {
        // 一旦找到时间大于当前时间的歌词行，就停止查找
        break;
      }
    }
    
    return currentIndex;
  }

  /// 获取当前歌词文本
  static String getCurrentLyricText(List<LyricLine> lyrics, Duration currentTime) {
    final index = getCurrentLyricIndex(lyrics, currentTime);
    if (index >= 0 && index < lyrics.length) {
      return lyrics[index].text;
    }
    return '';
  }
}